const path = require('path')
const isProd = process.env.NODE_ENV === 'production' // production: 生产环境  development：开发环境
const UglifyJsPlugin = require('uglifyjs-webpack-plugin') // 去掉注释
const CompressionWebpackPlugin = require('compression-webpack-plugin') // gzip格式压缩
const { HashedModuleIdsPlugin } = require('webpack') // 只打包改变的文件

function resolve(dir) {
  return path.join(__dirname, dir)
}

module.exports = {
  productionSourceMap: false, // 关闭生产环境的 source map 以加速生产环境构建
  publicPath: isProd ? './' : '',
  chainWebpack: (config) => {
    // 设置别名
    config.resolve.alias
      .set('@', resolve('src'))
      .set('assets', resolve('src/assets'))
      .set('views', resolve('src/views'))
      .set('components', resolve('src/components'))

    config.optimization.delete('splitChunks')
  },
  configureWebpack: (config) => {
    const plugins = []

    // 开发阶段时不会配置if中的东西
    if (isProd) {
      plugins.push(
        new UglifyJsPlugin({
          uglifyOptions: {
            output: {
              comments: false, // 去掉注释
            },
            warnings: false,
            compress: {
              drop_console: true,
              drop_debugger: false,
              pure_funcs: ['console.log'], //移除console
            },
          },
        })
      )

      // 配置webpack压缩
      plugins.push(
        new CompressionWebpackPlugin({
          test: /\.js$|\.html$|\.css$/,
          deleteOriginalAssets: false, // 不删除源文件
          // 超过4kb压缩
          threshold: 4096,
        })
      )

      // 开启分离js
      config.optimization = {
        runtimeChunk: 'single',
        splitChunks: {
          chunks: 'all',
          maxInitialRequests: Infinity,
          minSize: 1000 * 60,
          cacheGroups: {
            vendor: {
              test: /[\\/]node_modules[\\/]/,
              name(module) {
                // 排除node_modules 然后吧 @ 替换为空 ,考虑到服务器的兼容
                const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
                return `npm.${packageName.replace('@', '')}`
              },
            },
          },
        },
      }

      // 用于根据模块的相对路径生成 hash 作为模块 id, 一般用于生产环境
      plugins.push(new HashedModuleIdsPlugin())
    }
    return { plugins }
  },
}
